package net.qunzhi.modules.historyspider;


import net.qunzhi.modules.cms.entity.TbEquipmentEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class HistorySpiderStarter {


    // '2010-01-01 00:00:00'
    private static final String beginTime = "2018-01-01 00:00:00";
//    private static final String url = "http://127.0.0.1:33388/data/index.php"; // 本地地址
    private static final String url = "http://192.168.3.19/data/index.php";// 线上地址
    protected static Logger logger = LoggerFactory.getLogger(HistorySpiderStarter.class);

    public static synchronized void work(TbEquipmentEntity equipment, String maxtime, String spiderType, String tag) throws Exception {

        var equipmentId = equipment.getId();
//        String url = equipment.getUrl();
        var spiderStatus = equipment.getSpiderStatus();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //2019-08-27 19:21:10
        //获取数据库最大时间
        maxtime = maxtime == null ? HistorySpiderStarter.beginTime : maxtime;
        //用于计算每5次更新一下时间
        int i = 0;
        //获取对应equipment_id的最大的时间
        String maxday = maxtime.split(" ")[0];
        int maxYear = Integer.parseInt(maxday.split("-")[0]);
        int maxMonth = Integer.parseInt(maxday.split("-")[1]);
        int maxDay = Integer.parseInt(maxday.split("-")[2]);

        //获取今天数据
        Date nowDate = new Date();
        String splitNowDate = dateFormat.format(nowDate);
        String[] nows = splitNowDate.split("-");
        int nowYear = Integer.parseInt(nows[0]);
        int nowMonth = Integer.parseInt(nows[1]);
        int nowDay = Integer.parseInt(nows[2]);
        //获取明天日期
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, 1);
        String tomorrow = dateFormat.format(calendar.getTime());
        HttpClient client = null;
        client = HttpClientBuilder.create().build();

        //http://localhost:8083/data/index.php?year=2010&month=03&mday=04&tagname=dtag000899
        String month = "";
        String mday = "";
        String year = "";
        try {
            for (int y = maxYear; y <= nowYear; y++) {
                for (int m = 1; m <= 12; m++) {
                    for (int d = 1; d <= 31; d++) {
                        if (m < 10) {
                            month = "0" + m;
                        } else {
                            month = "" + m;
                        }
                        if (d < 10) {
                            mday = "0" + d;
                        } else {
                            mday = "" + d;
                        }
                        year = y + "";
                        String todate = year + "-" + month + "-" + mday;
                        if (todate.compareTo(maxday) >= 0 && todate.compareTo(tomorrow) < 0) {
                            String urled = url + "?tagname=" + tag + "&year=" + year + "&month=" + month + "&mday=" + mday;
                            //System.out.println("正在爬取"+ year + "-" + month + "-" + mday + "的数据");
                            Date beginSpiderTime = new Date();
                            System.out.println(todate+"开始启动");
                            //启动方法
                            XjSpider.start(urled, client, equipmentId, maxtime, spiderType);

                            // 如果达到5次那么就更新一次时间，将i置0，否则继续递增
                            while (0 < i && i <= 5 ) {
                                if (i == 5) {
                                    Date endSpiderTime = new Date();
                                    Long between = (endSpiderTime.getTime() - beginSpiderTime.getTime()) / 1000;
                                    //获取一次页面所需的时间min
                                    float min = (float) between / 60;
                                    long num = (endSpiderTime.getTime() - dateFormat.parse(todate).getTime()) / (1000 * 60 * 60 * 24);
                                    int time = Math.round(num * min);
                                    SpiderTimer.setSpiderTimer(String.valueOf(time), "0", String.valueOf(equipmentId));
                                    i = 0;
                                } else {
                                    i++;
                                }
                            }
                            //更新设备爬状态，此时爬取未完成
//                            if (spiderStatus == null || "".equals(spiderStatus) || "0".equals(spiderStatus)) {
//                                equipment.setSpiderStatus(Constant.EquipmentSpiderStatus.INCOMPLETE.getCode());
//                                try {
//                                    equipmentService.insertOrUpdateSpiderStatus(equipment);
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                                spiderStatus = Constant.EquipmentSpiderStatus.INCOMPLETE.getCode();
//                            }
                        }
                    }
                }
            }

            //更新设备爬状态，此时爬取完成

           /* equipment.setSpider_status("1");
            try {
                equipmentService.insertOrUpdateSpiderStatus(equipment);
            } catch (AlreadyExistsException e) {
                e.printStackTrace();
            }*/


            //在此处可以进行更改设备情况
            SpiderTimer.setSpiderTimer("-1", "1", "0");

        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new Exception("网络异常");
        } finally {
            //在此处可以进行更改设备情况
            SpiderTimer.setSpiderTimer("-1", "1", "0");

        }
    }

    public synchronized void test () {


    }
}
